import random
import hashlib

''' 随机生成指定长度字符串 '''
def create_nonce_str(length = 6):
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return "".join(random.sample(chars, length))

''' md5加密 '''
def md5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()

''' 创建用户密码 '''
def create_password(password, salt = ""):
    return md5(md5(password) + salt)

''' 生成树 '''
def generate_tree(data, parent_id = 0):
    tree = []
    for item in data:
        if item['parent_id'] == parent_id:
            item['children'] = generate_tree(data, item['id'])
            tree.append(item)
    return tree

if __name__ == "__main__":
    pass
    #print(create_password('admin'))

    a = [
        {"id": 1, "name": '电器', "parent_id": 0},
        {"id": 2, "name": '水果', "parent_id": 0},
        {"id": 3, "name": '家用电器', "parent_id": 1},
        {"id": 4, "name": '电吹风', "parent_id": 3},
        {"id": 5, "name": '电风扇', "parent_id": 3},
        {"id": 6, "name": '台灯', "parent_id": 3},
        {"id": 7, "name": '商用电器', "parent_id": 1},
        {"id": 8, "name": '大型电热锅', "parent_id": 7},
    ]
    print(generate_tree(a))